package org.presstrack.service
{
	import flash.net.NetConnection;
	import flash.net.Responder;
	
	import mx.collections.ArrayCollection;
	import mx.collections.Sort;
	import mx.utils.ObjectUtil;
	
	import org.presstrack.*;
	import org.presstrack.vos.*;
	
	import presstrack.*;
	import presstrack.targets.PressTargetClass;
	import presstrack.vos.*;
	
	[Bindable]	
	public class CrudService
	{
		/**
     	 * to communicate with the server
     	 */
		public var srv:NetConnection = new NetConnection;
		
		/**
     	 * 
     	 */
		public static var crud:CrudService = new CrudService;
		
		/**
     	 * version number
     	 */
		public static var version:String = new String("ver. 2.0.3");
		
		/**
     	 * revision number
     	 */
		public static var revision:String = new String("rev. 54");
		
		/**
     	 * this company name
     	 */
		public static var company:String = new String;
		
		/**
     	 * user is logged in
     	 */
		public static var curUser:UserClass = new UserClass;
		
		/**
     	 * order with which the user is currently running
     	 */
		public static var curOrder:OrderClass = new OrderClass;
		
		/**
     	 * current orders - off the ground
     	 */
		public static var arCurOrder:ArrayCollection = new ArrayCollection;		
		
		/**
     	 * true when current orders are loaded
     	 * false by default and if server returned error message
     	 */
		public static var isCurOrderLoad:Boolean = new Boolean;
		
		/**
     	* store - ready-made orders
     	*/
		public static var arStoreOrder:ArrayCollection = new ArrayCollection;
		
		/**
     	 * true when store orders are loaded
     	 * false by default and if server returned error message
     	 */
		public static var isAllOrderLoad:Boolean = new Boolean;
		
		/**
     	 * a list of years from creation date of orders
     	 * current year by default
     	 */
		public static var arAllYear:ArrayCollection = new ArrayCollection([ {label:(new Date().getFullYear()).toString()} ]);
		 
		/**
     	 * customer list
     	 */
		public static var arCustomer:ArrayCollection = new ArrayCollection;
		
		/**
     	 * true when customers are loaded
     	 * false by default and if server returned error message
     	 */
		public static var isCustomerLoad:Boolean = new Boolean;
		
		/**
     	 * list of available operations
     	 */
		public static var arOperation:ArrayCollection = new ArrayCollection;
		
		/**
     	 * list of papers
     	 */
		public static var arPaper:ArrayCollection = new ArrayCollection;
		
		/**
     	 * true when papers are loaded
     	 * false by default and if server returned error message
     	 */
		public static var isPaperLoad:Boolean = new Boolean;
		
		/**
     	 * delivery of papers
     	 */
		public static var arDelivery:ArrayCollection = new ArrayCollection;
		
		/**
     	 * delivery of papers
     	 */
		public static var arIssue:ArrayCollection = new ArrayCollection;
		
		/**
     	 * true when papers issue are loaded
     	 * false by default and if server returned error message
     	 */
     	public static var isIssueLoad:Boolean = new Boolean;
		
		public static var arCurRequest:ArrayCollection = new ArrayCollection;
		
		/**
     	 * true when request on papers issue for current orders are loaded
     	 * false by default and if server returned error message
     	 */
		public static var isCurRequestLoad:Boolean = new Boolean;
		
		public static var arAllRequest:ArrayCollection = new ArrayCollection;
		
		/**
     	 * true when store of papers request are loaded
     	 * false by default and if server returned error message
     	 */
		public static var isAllRequestLoad:Boolean = new Boolean;
		
		/**
     	 * statistic report for general section
     	 */
		public static var reportGeneral:ReportGeneralClass = new ReportGeneralClass;
		
		/**
     	 * statistic report for sale section
     	 */
		public static var reportSale:ReportSaleClass = new ReportSaleClass;
		
		/**
     	 * statistic report for payment section
     	 */
		public static var reportPayment:ReportPaymentClass = new ReportPaymentClass;
		
		/**
     	 * statistic report for operation section
     	 */
		public static var reportOperation:ReportOperationClass = new ReportOperationClass;
		
		/**
     	 * plan for press section
     	 */
		public static var arPlanPress:ArrayCollection = new ArrayCollection;
		
		
		
		
		
		
		
		
		
		
		
		public static var arOperationByCustomer:ArrayCollection	= new ArrayCollection;
				
		
		public static var arSupplier:ArrayCollection	= new ArrayCollection;
		public static var arPayer:ArrayCollection		= new ArrayCollection;
		
		public static var arPayment:ArrayCollection		= new ArrayCollection;
		public static var arManager:ArrayCollection		= new ArrayCollection;		
		public static var isPaymentLoad:Boolean			= new Boolean;		
		public static var isTrackLoad:Boolean			= new Boolean;		
		
		public static var statistic:StatisticVO			= new StatisticVO;
		public static var orders_price:String			= new String;
		public static var count_of_order:String			= new String;
		public static var payments_sum:String			= new String;
		public static var orders_debt:String			= new String;
		public static var managers_stat:ArrayCollection		= new ArrayCollection;
		public static var customer_cost:ArrayCollection		= new ArrayCollection;
		public static var customer_num:ArrayCollection		= new ArrayCollection;
		public static var customer_pay_debt:ArrayCollection		= new ArrayCollection;
		public static var prepress_operation:ArrayCollection	= new ArrayCollection;
		public static var postpress_operation:ArrayCollection	= new ArrayCollection;
		public static var press_operation:ArrayCollection		= new ArrayCollection;
		public static var pay_array:ArrayCollection	= new ArrayCollection;
		public static var cost_array:ArrayCollection = new ArrayCollection;
		
		public static const MILLISECONDS_PER_MINUTE:int 	= 1000 * 60; 
		public static const MILLISECONDS_PER_HOUR:int 		= 1000 * 60 * 60; 
		public static const MILLISECONDS_PER_DAY:int 		= 1000 * 60 * 60 * 24;
		
		/**
		 * 
		 *******************************     *******************************
		 * 
		 * */
		 
		public function CrudService() 
		{
		}
		
		public function connect(host:String):void 
		{
			srv.connect(host + "amfphp/gateway.php");
		}				
		
		/**
		 * 
		 * user authorisation  
		 * 
		 * section:
		 * 		1 - manager
		 * 		2 - store
		 * 		3 - prepress
		 * 		4 - press
		 * 		5 - postpress
		 * 		6 - destination
		 * 		7 - payment
		 * 		8 -	customers 
		 * 		9 - report
		 * 	   10 - track
		 * */		 
		public function loginUser(user		:String, 
								  pass		:String, 		
								  section	:String, 
								  resFunc	:Function	= null, 
								  faultFunc	:Function	= null):void								  
		{
			srv.call("PressTrack.LoginUser", new Responder(onResult, onFault), user, pass, section);
			
			function onResult(result:Object):void 
			{
				if (result.status == true) 
				{					
					CrudService.curUser = new UserClass(result.user);
					
					if (resFunc != null)
					{
						resFunc();
					}
															
					var mon:String = (new Date().getMonth() + 1).toString();
    				if (mon.length == 1)
					{
						mon = "0" + mon;
					}
					
					switch (section) {
						case "1" :
							CrudService.crud.getAllYear();
							CrudService.crud.getOrders("cur_orders", (new Date().getFullYear()).toString());
							CrudService.crud.getCustomers((new Date().getFullYear()).toString());							
							CrudService.crud.getOperation();
							CrudService.crud.getPapers();
						break;
						
						case "2" :
							CrudService.crud.getAllYear();
							CrudService.crud.getPapers();
							CrudService.crud.getPaperPayers();
							CrudService.crud.getPaperSuppliers();
							
							CrudService.crud.getCurRequest();		
							CrudService.crud.getAllRequest(new Date().getFullYear());							
							CrudService.crud.getManager(CrudService.curUser.iUserId);
						break;
						
						case "7" :
							CrudService.crud.getAllYear();
							CrudService.crud.getPayers();
							CrudService.crud.getOrders("all", (new Date().getFullYear()).toString());
							CrudService.crud.getPayments((new Date().getFullYear()).toString());							
							CrudService.crud.getIssue();													
						break;
												
						case "9" :
							CrudService.crud.getAllYear();
							CrudService.crud.getGeneralReport((new Date().getFullYear()).toString(), mon);
						break;
						
						case "10" :
							//CrudService.crud.getTracker();
							//CrudService.crud.getPlans();
						break;												
					}					
				}
				else if (faultFunc != null)
				{
					faultFunc(result.message);
				}
			}
			
			function onFault(e:Object) : void {
				faultFunc(ObjectUtil.toString(e));
			}				
		}
		
		/**
		 * 
		 ******************************* GET *******************************
		 * 
		 * */
		
		/**
		 * 
		 * read a list of years when they were created orders 
		 * in CrudService.arAllYear  
		 * 
		 * */ 
		public function getAllYear():void 
		{
			srv.call("PressTrack.GetYear", new Responder(onResult));			
			
			function onResult(ar:Array):void 
			{
				CrudService.arAllYear = new ArrayCollection(ar);
				CrudService.arAllYear.refresh();
			}
		}
		
		/**
		 * 
		 * read a order in CrudService.curOrder
		 * 
		 * */ 
		public function getOrder(order_id	:int, 
								 ind		:int, 
								 resFunc	:Function	= null, 
								 faultFunc	:Function	= null):void 
		{
			srv.call("PressTrack.GetOrder", new Responder(onResult, onFault), order_id);
			
			function onResult(st:Object):void 
			{
				CrudService.curOrder = new OrderClass(st);
				if (ind != -1)
				{
					CrudService.arCurOrder[ind] = CrudService.curOrder;
					CrudService.arCurOrder.refresh();
				}				
				
				if (resFunc != null)
				{
					resFunc();
				}
			}
			
			function onFault(e:Object):void 
			{
				if (faultFunc != null)
				{
					faultFunc(ObjectUtil.toString(e));
				}
			}
		}
		
		/**
		 * 
		 * read a current orders in CrudService.arCurOrder 
		 * 
		 * */
		public function getOrders(table		:String, 
								  year		:String, 
								  resFunc	:Function	= null, 
								  faultFunc	:Function	= null):void 
		{
			srv.call("PressTrack.GetOrders", new Responder( onResult, onFault ), curUser.iUserId, table, year);
						
			function onResult(st:Array):void 
			{
				switch (table) {
					case "cur_orders": 
						CrudService.arCurOrder = new ArrayCollection();
						for each (var ob:Object in st) 
						{
							var order:OrderClass = new OrderClass(ob);
							CrudService.arCurOrder.addItem(order);
						}						
						CrudService.arCurOrder.refresh();
						CrudService.isCurOrderLoad = true;	
					break;	
					
					case "store_orders" :
					case "all" :
						CrudService.arStoreOrder = new ArrayCollection();
						for each (var store_ob:Object in st) 
						{
							var store_order:OrderClass = new OrderClass(store_ob);
							CrudService.arStoreOrder.addItem(store_order);
						}
						CrudService.arStoreOrder.refresh();
						CrudService.isAllOrderLoad = true;
					break;
				}	
				
				if (resFunc != null)
				{
					resFunc();
				}					
			}
			
			function onFault(e:Object):void 
			{
				faultFunc(ObjectUtil.toString(e));
			}
		}
		
		public function getCustomers(year		:String, 
									 resFunc	:Function	= null, 
									 faultFunc	:Function	= null):void 
		{
			srv.call("PressTrack.GetCustomers", new Responder(onResult, onFault), CrudService.curUser.iUserId, year);			
			
			function onResult(st:Array):void 
			{
				CrudService.arCustomer = new ArrayCollection();
				for each(var ob:UserClass in st) {
					var cust:CustomerClass = new CustomerClass(ob);
					CrudService.arCustomer.addItem(cust);
				}				
				CrudService.arCustomer.refresh();
				CrudService.isCustomerLoad = true;
				if (resFunc != null)
				{
					resFunc();
				}
			}
			
			function onFault(e:Object):void 
			{
				faultFunc(ObjectUtil.toString(e));
			}
		}
		
		public function getOperation():void 
		{
			srv.call("PressTrack.GetOperation", new Responder(onResult));			
			
			function onResult(ar:Array):void 
			{
				CrudService.arOperation = new ArrayCollection(ar);
			}
		}
		
		public function getPapers(resFunc	:Function	= null, 
								  faultFunc	:Function	= null):void 
		{
			srv.call("PressTrack.getPapers", new Responder(onResult));
			
			function onResult(ar:Array):void 
			{
				CrudService.arPaper 	= new ArrayCollection();
				CrudService.arDelivery	= new ArrayCollection();
				CrudService.arIssue		= new ArrayCollection();
				for each(var p:PaperClass in ar)
				{
					var paper:PaperClass = new PaperClass(p);
					CrudService.arPaper.addItem(paper);
				}
				CrudService.arPaper.refresh();
				CrudService.isPaperLoad	= true;
				if (resFunc != null)
				{
					resFunc();
				}
			}
		}
		
		public function getPayments(year		:String,
									resFunc		:Function	= null):void 
		{
			srv.call("PressTrack.getPayments", new Responder(onResult), "-1", year);			
			
			function onResult(st:Array):void 
			{
				CrudService.arPayment = new ArrayCollection();
				for each (var ob:Object in st)
				{
					var payment:PaymentClass = new PaymentClass(ob);
					CrudService.arPayment.addItem(payment);
				}
				CrudService.arPayment.refresh();
				CrudService.isPaymentLoad = true;
				if (resFunc != null)
				{
					resFunc();
				}
			}
		}
		
		public function getPayers():void 
		{
			srv.call("PressTrack.GetPayers", new Responder(onResult));			
			
			function onResult(st:Array):void 
			{
				CrudService.arCustomer = new ArrayCollection(st);
				CrudService.arCustomer.refresh();
			}
		}
		
		public function getCurRequest(resFunc	:Function	= null, 
								  	  faultFunc	:Function	= null):void  
		{
			srv.call("PressTrack.GetRequestForPaper", new Responder(onResult), "cur_request",  (new Date().getFullYear()).toString());
			
			function onResult(st:Array):void 
			{
				var pattern:RegExp = /[^0-9]/g;
				for each (var req:Object in st) 
				{
					var ar_run_part:Array = req.press.press_run.split(/,/);
					var run:int = 0;
					for each (var r:Object in ar_run_part)
					{						
						var ar_run:Array = r.split(/x/);
						if (ar_run.length > 1)
						{
							ar_run[0] 	= ar_run[0].replace(pattern,'');
							ar_run[1] 	= ar_run[1].replace(pattern,'');
							run			= run + (Number(ar_run[0]) * Number(ar_run[1]));
						} 
						else 
						{
							ar_run[0] 	= ar_run[0].replace(pattern,'');
							run			= run + Number(ar_run[0]);
						}
					}
				
					var waste:int = 0;
					var ar_waste_part:Array	= req.press.press_waste.split(/,/);
					for each (var w:Object in ar_waste_part)
					{
						var ar_waste:Array	= w.split(/x/);
						if (ar_waste.length > 1)
						{
							ar_waste[0]	= ar_waste[0].replace(pattern,'');
							ar_waste[1]	= ar_waste[1].replace(pattern,'');
							waste		= waste + (Number(ar_waste[0]) * Number(ar_waste[1]));
						} 
						else 
						{
							ar_waste[0] = ar_waste[0].replace(pattern,'');                    	
							waste		= waste + Number(ar_waste[0]);
						}
					}
				
					var ar_cut:Array 	= req.paper.paper_cut.split("/");
					var cut:int			= ar_cut[0] * ar_cut[1];				
					req.total			= int ((run + waste) / cut);					
				}
				CrudService.arCurRequest = new ArrayCollection(st);
				CrudService.arCurRequest.refresh();
				CrudService.isCurRequestLoad = true;
				
				PaperClass.refreshNumOfReq();
				
				if (resFunc != null)
				{
					resFunc();
				}
			}
		}	
		
		/* 
		function	:	getAllRequest
		description :	возвращает из бд все заявки 
		*/
		public function getAllRequest(year		:int,
									  resFunc	:Function	= null, 
								      faultFunc	:Function	= null):void 
		{
			srv.call("PressTrack.GetRequestForPaper", new Responder(onResult), "all_request", year);
			
			function onResult(st:Array):void 
			{
				var pattern:RegExp = /[^0-9]/g;
				for each (var req:Object in st) {
					var ar_run_part:Array = req.press.press_run.split(/,/);
					var run:int = 0;
					for each(var r:Object in ar_run_part)
					{
						var ar_run:Array	= r.split(/x/);
						if (ar_run.length > 1)
						{
							ar_run[0] = ar_run[0].replace(pattern,'');
							ar_run[1] = ar_run[1].replace(pattern,'');
							run	= run + (Number(ar_run[0]) * Number(ar_run[1]));
						}
						else
						{
							ar_run[0] = ar_run[0].replace(pattern,'');
							run	= run + Number(ar_run[0]);
						}
					}
				
					var waste:int = 0;
					var ar_waste_part:Array	= req.press.press_waste.split(/,/);
					for each(var w:Object in ar_waste_part)
					{
						var ar_waste:Array	= w.split(/x/);
						if (ar_waste.length > 1)
						{
							ar_waste[0] = ar_waste[0].replace(pattern,'');
							ar_waste[1] = ar_waste[1].replace(pattern,'');
							waste = waste + ( Number(ar_waste[0]) * Number(ar_waste[1]) );
						}
						else
						{
							ar_waste[0] = ar_waste[0].replace(pattern,'');
                    		waste = waste + Number(ar_waste[0]);
						}
					}
				
					var ar_cut:Array = req.paper.paper_cut.split("/");
					var cut:int = ar_cut[0] * ar_cut[1];
				
					req.total = int ((run + waste) / cut);
				}
				CrudService.arAllRequest = new ArrayCollection(st);
				CrudService.arAllRequest.refresh();
				CrudService.isAllRequestLoad = true;
				
				PaperClass.refreshNumOfDel();
				
				if (resFunc != null)
				{
					resFunc();
				}
			}
		}
		
		public function getPaperSuppliers():void 
		{
			srv.call("PressTrack.GetPaperSuppliers", new Responder(onResult));			
			function onResult(st:Array):void
			 {
				CrudService.arSupplier = new ArrayCollection(st);
				CrudService.arSupplier.refresh();
			}
		}
		
		public function getPaperPayers():void 
		{
			srv.call("PressTrack.GetPaperPayers", new Responder(onResult));				
			function onResult( st:Array ):void 
			{
				CrudService.arPayer = new ArrayCollection(st);
				CrudService.arPayer.refresh();
			}
		}
		
		public function getIssue():void 
		{
			srv.call("PressTrack.GetIssue", new Responder(onResult));			
			
			function onResult(st:Array):void 
			{
				CrudService.arIssue = new ArrayCollection();
				for each (var ob:Object in st)
				{
					var issue:PaperIssueClass = new PaperIssueClass(ob);
					CrudService.arIssue.addItem(issue);
				}
				CrudService.isIssueLoad = true;
			}
		}	
		
		public function getGeneralReport(year		:String, 
										 month		:String,
										 resFunc	:Function	= null, 
								      	 faultFunc	:Function	= null):void
		{
			srv.call("PressTrack.GetGeneralReport", new Responder(onResult), year, month);			
			
			function onResult(result:Object):void 
			{
				if (result.status == true)
				{
					CrudService.reportGeneral = new ReportGeneralClass(result.report);
					if (resFunc != null)
					{
						resFunc();
					}
				}
				else
				{
					if (faultFunc != null)
					{
						faultFunc();
					}
				}
			}			
		}
		
		public function getSaleReport(year		:String,
									  resFunc	:Function	= null, 
								      faultFunc	:Function	= null):void
		{
			srv.call("PressTrack.GetSaleReport", new Responder(onResult), year);			
			
			function onResult(result:Object):void 
			{
				if (result.status == true)
				{
					CrudService.reportSale = new ReportSaleClass(result.report);
					if (resFunc != null)
					{
						resFunc();
					}
				}
				else
				{
					if (faultFunc != null)
					{
						faultFunc();
					}
				}
			}			
		}
		
		public function getPaymentReport(year		:String,
									  	 resFunc	:Function	= null, 
								      	 faultFunc	:Function	= null):void
		{
			srv.call("PressTrack.GetPaymentReport", new Responder(onResult), year);			
			
			function onResult(result:Object):void 
			{
				if (result.status == true)
				{
					CrudService.reportPayment = new ReportPaymentClass(result.report);
					if (resFunc != null)
					{
						resFunc();
					}
				}
				else
				{
					if (faultFunc != null)
					{
						faultFunc();
					}
				}
			}			
		}
		
		public function getOperationReport(year			:String,
										   section		:int,
									  	   resFunc		:Function	= null, 
								      	   faultFunc	:Function	= null):void
		{
			srv.call("PressTrack.GetOperationReport", new Responder(onResult), year, section);			
			
			function onResult(result:Object):void 
			{
				if (result.status == true)
				{
					CrudService.reportOperation = new ReportOperationClass(result.report);
					if (resFunc != null)
					{
						resFunc();
					}
				}
				else
				{
					if (faultFunc != null)
					{
						faultFunc();
					}
				}
			}			
		}
		
		/**
		 * 
		 * get current orders for tracker  
		 * 
		 * */
		public function getTracker(resFunc		:Function	= null, 
								   faultFunc	:Function	= null):void 
		{
			srv.call("PressTrack.GetTracker", new Responder(onResult, onFault));
			
			function onResult(result:Object):void 
			{
				if (result.status == true)
				{
					CrudService.arCurOrder = new ArrayCollection();
					for each (var tr:Object in result.tracker)
					{
						var track:TrackClass = new TrackClass(tr);
						CrudService.arCurOrder.addItem(track);						
					}
					CrudService.arCurOrder.refresh();
					if (resFunc != null)
					{
						resFunc();
					}
				}
				else
				{
					if (faultFunc != null)
					{
						faultFunc(result.message);
					}
				}				
			}
			
			function onFault(e:Object):void 
			{
				faultFunc(ObjectUtil.toString(e));
			}
		}
		
		/**
		 * 
		 * get plan for press section  
		 * 
		 * */
		public function getPlanPress(resFunc		:Function	= null, 
								     faultFunc		:Function	= null):void 
		{
			srv.call("PressTrack.getPlans", new Responder(onResult));
			
			function onResult(result:Object):void 
			{
				if (result.status == true)
				{
					CrudService.arPlanPress = new ArrayCollection();
					for each (var t:Object in result.plan)
					{
						var trg:PressTargetClass = new PressTargetClass(t);
						CrudService.arPlanPress.addItem(trg);										
					}
					
					CrudService.arPlanPress.filterFunction = filterForPressTraget;
					var sort:Sort = new Sort();
					sort.compareFunction = comparePressTargetFunc;
					CrudService.arPlanPress.sort = sort;	
					CrudService.arPlanPress.refresh();
					
					function comparePressTargetFunc(a		:Object, 
													b		:Object, 
													fields	:Array = null):int
					{
						return a.compare(b);
					}
					
					if (resFunc != null)
					{
						resFunc();
					}
				}
				else
				{
					if (faultFunc != null)
					{
						faultFunc(result.message);
					}
				}															
			}			
		}		
		
		/**
		 * 
		 ******************************* ADD *******************************
		 * 
		 * */
		
		/**
		 * 
		 * write new order into database  
		 * 
		 * */
		public function addOrder(template	:int, 
								 resFunc	:Function	= null, 
								 faultFunc	:Function	= null):void 
		{
			srv.call("PressTrack.AddOrder", new Responder(onResult, onFault), 
					 CrudService.curUser.iUserId, template);	
			
			function onResult(result:Object):void 
			{
				if (result.status == true)
				{
					var order:OrderClass = new OrderClass(result.order);
					CrudService.arCurOrder.addItem(order);
					CrudService.arCurOrder.refresh();
					CrudService.curOrder = CrudService.arCurOrder[CrudService.arCurOrder.length - 1];
					if (resFunc != null)
					{
						resFunc();
					} 
				}
				else
				{
					faultFunc(result.message);
				}
			}
			
			function onFault(e:Object) : void 
			{
				faultFunc(ObjectUtil.toString(e));
			}					
		}
		
		public function addCustomer(resFunc		:Function, 
									faultFunc	:Function):void 
		{
			srv.call("PressTrack.AddCustomer", new Responder(onResult, onFault), 
					 CrudService.curUser.iUserId);			
			
			function onResult(id:int):void 
			{
				if (Number(id)) 
				{
					var customer:CustomerClass = new CustomerClass();
					customer.iUserId = Number(id);
					CrudService.arCustomer.addItem(customer);
					CrudService.arCustomer.refresh();
					if (resFunc != null)
					{
						resFunc();
					}
				}
				else
				{
					faultFunc(id);
				}
			}
			
			function onFault(e:Object):void 
			{
				faultFunc(ObjectUtil.toString(e));
			}
		}
		
		public function addDelivery(delivery	:Object, 
									resFunc		:Function	= null, 
									faultFunc	:Function	= null):void 
		{
			CrudService.crud.srv.call("PressTrack.AddDelivery", new Responder(onResult, onFault),
									 delivery.invoice, delivery.creation, 
									 delivery.label, delivery.thick, 
									 delivery.size, delivery.num, 
									 delivery.supplier, delivery.payer, 
									 delivery.sum, delivery.cost);	
			
			function onResult(result:Object):void
			{
				if (result.status == true) 
				{
					var res:Boolean = false;
					for each (var p:PaperClass in CrudService.arPaper)
					{
						if (p.iPaperId == result.paper_id)
						{
							delivery.iddelivery = result.iddelivery;
							var del:PaperDeliveryClass = new PaperDeliveryClass(delivery);
							p.arDelivery.addItem(del);
							p.arDelivery.refresh();
							CrudService.arDelivery.addItem(del);
							CrudService.arDelivery.refresh();
							p.iTotal = result.paper_total;
							res = true;
							break;
						}					
					}
					
					if (!res)
					{
						CrudService.crud.getPapers(resFunc, faultFunc);
					}
					else if (resFunc != null)
					{
						resFunc();
					}
					
				}
				else
				{
					faultFunc(result.message);
				}
			}
			
			function onFault(e:Object) : void 
			{
				faultFunc(ObjectUtil.toString(e));
			}		
		}		
		
		/**
		 * 
		 ***************************** REMOVE *****************************
		 * 
		 * */
		
		public function removeOrder(orderId		:int, 
									resFunc		:Function	= null, 
									faultFunc	:Function	= null):void 
		{
			srv.call("PressTrack.RemoveOrder", new Responder(resFunc), orderId);			
		}
		
		public function removePayment(paymentId :int, 
									  resFunc	:Function	= null, 
									  faultFunc	:Function	= null):void
		{
			srv.call("PressTrack.RemovePayment", new Responder( onResult, onFault ), paymentId);
			
			function onResult(res:String):void 
			{
				for each (var p:PaymentClass in CrudService.arPayment)
				{
					if (p.iPaymentId == paymentId)
					{
						CrudService.arPayment.removeItemAt(CrudService.arPayment.getItemIndex(p));
						CrudService.arPayment.refresh();
					}
				}
									
				if (res == 'successful') 
				{
					if (resFunc != null)
					{
						resFunc();
					}					
				}
				else	
				{
					faultFunc(res);	
				}		
			}
			
			function onFault(e:Object) : void 
			{
				faultFunc(ObjectUtil.toString(e));
			}
		}
		
		public function removeIssue(idissue		:int, 
									resFunc		:Function	= null, 
									faultFunc	:Function	= null):void
		{
			srv.call("PressTrack.RemoveIssue", new Responder(onResult, onFault), idissue);
			
			function onResult(res:String):void 
			{
				if (res == 'successful') 
				{
					for each (var iss:PaperIssueClass in CrudService.arIssue)
					{
						if (iss.iIssueId == idissue)
						{
							CrudService.arIssue.removeItemAt(CrudService.arIssue.getItemIndex(iss));
							break;
						}				
					}
					CrudService.arIssue.refresh();
				}
				else	
				{
					faultFunc(res);	
				}		
			}
			
			function onFault(e:Object):void 
			{
				faultFunc(ObjectUtil.toString(e));
			}
		}
		
		public function removeDelivery(iddelivery	:int, 
									   resFunc		:Function	= null, 
									   faultFunc	:Function	= null):void
		{
			srv.call("PressTrack.removeDelivery", new Responder(onResult, onFault), iddelivery);
			
			function onResult(res:String):void 
			{
				if (res == 'successful') 
				{
					CrudService.crud.getPapers(resFunc, faultFunc);
				}
				else	
				{
					faultFunc(res);	
				}		
			}
			
			function onFault(e:Object):void 
			{
				faultFunc(ObjectUtil.toString(e));
			}
		}
		
		/**
		 * 
		 ******************************* UPDATE *******************************
		 * 
		 * */	
		
		public function updateDebts(resFunc		:Function	= null, 
									faultFunc	:Function	= null):void 
		{
			srv.call("PressTrack.CalculateDebtOfOrders", new Responder(onResult));
			
			function onResult(res:String):void 
			{
				if (res == 'successful') 
				{
					CrudService.crud.getPayers();
					CrudService.crud.getOrders("all", (new Date().getFullYear()).toString());
					
					if (resFunc != null)
					{
						resFunc();					
					}
				}
				else
				{
					resFunc();
				}
			}
		}
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		/////////////////////////////// READ ///////////////////////////////
		/* 
		function	:	getStatistic
		description :	возвращает статистику за данный месяц данного года по конкретному менеджеру, или по всему отделу продаж
		
		public function getStatistic(year:String, month:String, manager:int = 0, resFunc:Function = null, faultFunc:Function = null):void {
			if (manager != 0)
				srv.call( "PressTrack.getManagerStatistic", new Responder( onResultManager, onFault ), manager, year, month );
			else
				srv.call( "PressTrack.getStatistic", new Responder( onResultAll ), year, month );			
			
			function onResultManager( result:Object ):void {
				if (result.status == true)
				{
					CrudService.statistic = new StatisticVO(result.statistic);
					if (resFunc != null) resFunc();
				}
				else if (faultFunc != null) faultFunc(result.message);											
			}
			
			function onResultAll( st:Array ):void {
				CrudService.orders_price 		= Number(st[0].orders_price).toFixed(2);	
				CrudService.count_of_order		= st[0].count_of_order;
				CrudService.payments_sum		= Number(st[0].payments_sum).toFixed(2);
				CrudService.orders_debt			= Number(st[0].orders_debt).toFixed(2);	
				
				CrudService.managers_stat		= new ArrayCollection(st[0].managers);
				CrudService.customer_cost		= new ArrayCollection(st[0].customer_cost);
				CrudService.customer_num		= new ArrayCollection(st[0].customer_num);
				CrudService.customer_pay_debt	= new ArrayCollection(st[0].customer_pay_debt);
				CrudService.prepress_operation	= new ArrayCollection(st[0].prepress_operation);
				CrudService.postpress_operation = new ArrayCollection(st[0].postpress_operation);
				CrudService.press_operation		= new ArrayCollection(st[0].press_operation);
			}
			
			function onFault(e:Object) : void {
				if (faultFunc != null) faultFunc(ObjectUtil.toString(e));
			}
		}*/
		
		/*public function getPaper( idpaper:int, resFunc:Function = null, faultFunc:Function = null ) : void 
		{
			srv.call( "PressTrack.getPaper", new Responder( onResult ), idpaper);
			
			function onResult(ar:Array):void 
			{
				if(idpaper == -1)
					CrudService.arPaper = new ArrayCollection();
				
				for each(var ob:Object in ar)
				{
					var paper:PaperVO = new PaperVO(ob);
					if(idpaper != -1)
					{
						var res:Boolean = new Boolean();
						for each(var p:PaperVO in CrudService.arPaper)
						{
							if(p.idpaper == paper.idpaper)
							{
								p.setFrom(ob);
								res = true;
								break;
							}
						}
						if (!res) CrudService.arPaper.addItem(paper);
					}
					else
						CrudService.arPaper.addItem(paper);
				}
				
				CrudService.arPaper.refresh();
				CrudService.isPaperLoad = true;
				if (resFunc != null) resFunc();
			}
		}*/
		
		/* 
		function	:	getCurOrdersForTrack
		description :	возвращает трек-лист - список операций не закрытых заказов
		
		public function getCurOrdersForTrack():void {
			srv.call( "PressTrack.getCurOrdersForTrack", new Responder( onResult ));
			
			function onResult( ar:Array ) : void {
				CrudService.arStoreOrder = new ArrayCollection(ar);
				CrudService.isCurOrderLoad = true;				
			}
		}*/
		
		
		
		
		
		
		public function getCurrentDate() : String {
			var cur_date:String = new String;
    		cur_date = new Date().getDate().toString();
    		if (cur_date.length == 1)	
    			cur_date = "0" + cur_date;
    		var mon:String = (new Date().getMonth() + 1).toString();
    		if (mon.length == 1) mon = "0" + mon;
    		cur_date += "/"+ mon;
    		cur_date += "/" + (new Date().getFullYear()).toString();
    		return cur_date;
		}
		
		
		
		/* 
		function	:	getManager
		description :	возвращает из бд записи по менеджерам
		*/
		public function getManager( cur_user_id:int ) : void {
			this.getFromTable( cur_user_id, "manager", onResult );			
			function onResult( st:Array ):void {
				CrudService.arManager = new ArrayCollection(st);
				CrudService.arManager.refresh();
			}
		}
		
		/* 
		function	:	getManagerStatistics
		description :	возвращает из бд записи по менеджерам
		*/
		public function getManagerStatistics( year:String, iduser:int, resFunc:Function = null ) : void {
			srv.call( "PressTrack.getManagerStatistics", new Responder( onResult ), year, iduser );			
			function onResult( st:Array ):void {
				CrudService.arManager = new ArrayCollection(st);
				CrudService.arManager.refresh();
				if (resFunc != null) resFunc();
			}
		}
		
		public function getCustomerStatisticsTemp( year:String, manager_id:int, resFunc:Function = null ) : void {
			/*srv.call( "PressTrack.getCustomerStatisticsTemp", new Responder( onResult ), year, manager_id );			
			function onResult( st:Array ):void {
				CrudService.arCustomer = new ArrayCollection();
				for each(var ob:Object in st) {
					var cust:CustomerClass = new CustomerClass();
					cust.copyFrom(ob);
					CrudService.arCustomer.addItem(cust);
				}				
				CrudService.arCustomer.refresh();
				if (resFunc != null) resFunc();
			}*/
		}
		
		/* 
		function	:	getPayment
		description :	возвращает из бд платежи 
		*/
		public function getPaymentStatistics( cur_user_id:int, year:String, resFunc:Function = null ) : void {
			srv.call( "PressTrack.getPayment", new Responder( onResult ), cur_user_id, year );
			function onResult( st:Array ):void {
				CrudService.arPayment = new ArrayCollection(st);
				CrudService.arPayment.refresh();
				CrudService.isPaymentLoad = true;
				if (resFunc != null) resFunc();
			}
		}
		
		/* 
		function	:	getOperationStatistics
		description :	возвращает из бд операции 
		*/
		public function getOperationStatistics( year:String, resFunc:Function = null ) : void {
			srv.call( "PressTrack.getOperationStatistics", new Responder( onResult ), year );
			function onResult( st:Array ):void {
				CrudService.arOperation = new ArrayCollection(st);
				if (resFunc != null) resFunc();
			}
		}
		
		/* 
		function	:	getOperationByCustomerStatistics
		description :	возвращает из бд операции 
		*/
		public function getOperationByCustomerStatistics( year:String, month:String, operation:String, section:int, resFunc:Function = null ) : void {
			srv.call( "PressTrack.getOperationByCustomer", new Responder( onResult ), year, month, operation, section);
			function onResult( st:Array ):void {
				CrudService.arOperationByCustomer = new ArrayCollection(st);
				if (resFunc != null) resFunc();
			}
		}
		
		
		
		
		private function getFromTable( cur_user_id:int, table:String, func:Function ) : void {
			srv.call("PressTrack.getData", new Responder(func), cur_user_id, table);
		}
		
		////////////////////////////// filter function //////////////////////////////
		
		public function filterForPressTraget(it:PressTargetClass):Boolean
		{
			if (PressTargetClass.TARGET_ORDERID != -1)
				return (PressTargetClass.TARGET_ORDERID == it.iOrderId) ? true : false;
			
			if (PressTargetClass.TARGET_PRESS != "")
			{
				if (it.mPressLabel != PressTargetClass.TARGET_PRESS) return false;
			}
			
			if (PressTargetClass.TARGET_CUSTOMER != "")
			{
				if (it.mCustomer != PressTargetClass.TARGET_CUSTOMER) return false;
			}
			return true;
		}
		
		public function filterForDeliveryInStore(it:PaperDeliveryClass):Boolean 
		{
			var date:Array = it.mCreationDate.split("/");
			if (PaperDeliveryClass.DEL_YEAR != -1)
			{
				if (PaperDeliveryClass.DEL_YEAR != Number(date[2]))
				{
					return false;
				}
			}
			
			if (PaperDeliveryClass.DEL_MONTH != -1)
			{
				if (PaperDeliveryClass.DEL_MONTH != Number(date[1]))
				{
					return false;
				}
			}
			
			if (PaperDeliveryClass.DEL_START_DATE != "" 
			 && PaperDeliveryClass.DEL_END_DATE != "")
			{
				var arStartDate:Array 	= PaperDeliveryClass.DEL_START_DATE.split("/");
				var arEndDate:Array		= PaperDeliveryClass.DEL_END_DATE.split("/");
			
				if (Number(date[2]) < Number(arStartDate[2]) 
				 || Number(date[2]) > Number(arEndDate[2])) 
				{
					return false;
				}
				
				if (Number(date[2]) == Number(arStartDate[2])) 
				{
					if (Number(date[1]) < Number(arStartDate[1])) 
					{
						return false;
					}
					
					if (Number(date[1]) == Number(arStartDate[1]))
					{
						if (Number(date[0]) < Number(arStartDate[0])) 
						{
							return false;
						}
					}
				}
				
				if (Number(date[2]) == Number(arEndDate[2])) 
				{
					if (Number(date[1]) > Number(arEndDate[1]))
					{
						return false;
					}
					
					if (Number(date[1]) == Number(arEndDate[1]))
					{
						if (Number(date[0]) > Number(arEndDate[0]))
						{
							return false;
						}
					}
				}
			}
			
			var res:Boolean = new Boolean();
			if (PaperDeliveryClass.DEL_SUPPLIERS.length > 0)
			{				
				for each(var s:String in PaperDeliveryClass.DEL_SUPPLIERS)
				{
					if (s == it.mSupplier) res = true;
				}
				
				if (!res)
				{
					return false;
				}				
			}
						
			if (PaperDeliveryClass.DEL_PAYERS.length > 0)
			{
				res = new Boolean();
				for each (var p:Object in PaperDeliveryClass.DEL_PAYERS)
				{
					if (p.label == it.mPayer)  
					{
						res = true;
					}
				}
				
				if (!res)
				{
					return false;
				}	
			}						
			return true;
		}
		
		public function filterForDelivery(it:PaperDeliveryClass):Boolean 
		{
			var res:Boolean = new Boolean()
			if (PaperDeliveryClass.DEL_PAPERS.length > 0)
			{
				for each(var p:PaperClass in PaperDeliveryClass.DEL_PAPERS)
				{
					if (p.iPaperId == it.iPaperId)
					{
						res = true;
						break;
					}
				}
				if (!res)
				{
					return false;
				}
			}		
			res = filterForDeliveryInStore(it);				
			return res;
		}
		
		// for issue
		
		/* 
		function	:	filterForIssue
		description :	фильтрация отгрузок
		*/
		
		public function filterForIssueInStore(it:PaperIssueClass):Boolean 
		{
			
			
			var date:Array = it.mCreationDate.split("/");
			if (PaperIssueClass.ISSUE_YEAR != -1)
			{
				if (PaperIssueClass.ISSUE_YEAR != Number(date[2]))
				{
					return false;
				}
			}
			
			if (PaperIssueClass.ISSUE_MONTH != -1)
			{
				if (PaperIssueClass.ISSUE_MONTH != Number(date[1]))
				{
					return false;
				}
			}
			
			if (PaperIssueClass.ISSUE_START_DATE != "" 
			 && PaperIssueClass.ISSUE_END_DATE != "")
			{
				var arStartDate:Array 	= PaperIssueClass.ISSUE_START_DATE.split("/");
				var arEndDate:Array		= PaperIssueClass.ISSUE_END_DATE.split("/");
			
				if (Number(date[2]) < Number(arStartDate[2]) 
				 || Number(date[2]) > Number(arEndDate[2])) 
				{
					return false;
				}
				
				if (Number(date[2]) == Number(arStartDate[2])) 
				{
					if (Number(date[1]) < Number(arStartDate[1]))
					{ 
						return false;
					}
					if (Number(date[1]) == Number(arStartDate[1]))
					{
						if (Number(date[0]) < Number(arStartDate[0])) 
						{
							return false;
						}
					}
				}
				
				if (Number(date[2]) == Number(arEndDate[2])) 
				{
					if (Number(date[1]) > Number(arEndDate[1]))
					{
						return false;
					} 
					if (Number(date[1]) == Number(arEndDate[1]))
					{
						if (Number(date[0]) > Number(arEndDate[0]))
						{
							return false;
						}
					}
				}
			}
			
			return true;
		}
		
		public function filterForIssue(it:PaperIssueClass):Boolean 
		{
			if (PaperIssueClass.ISSUE_REQUEST != -1)
			{
				return (PaperIssueClass.ISSUE_REQUEST == it.iRequest) ? true : false;
			}
			
			var res:Boolean = new Boolean();
			res = filterForIssueInStore(it);
			if (res == false)
			{
				return false;
			}			
			
			if (PaperDeliveryClass.DEL_PAPERS.length > 0)
			{
				res = false;
				for each(var p:PaperClass in PaperDeliveryClass.DEL_PAPERS)
				{
					if (p.iPaperId == it.iPaperId)
					{
						res = true;
						break;
					} 
				}
			}				
			return res;
		}
		
		/* 
		function	:	filterIssueByManager
		description :	фильтрация отгрузок по заказам
		
		public function filterIssueByManager(it:Object) : Boolean {
			CrudService.arAllRequest.filterFunction = filterForReq;
			CrudService.arAllRequest.refresh();
			
			var man_name:String = new String;
			
			for each(var manager:Object in CrudService.arIssueManager) {
				man_name = manager.name;
				CrudService.arAllRequest.refresh();
				
				for each (var ob:Object in CrudService.arAllRequest) {
					if (ob.paper.idtask == it.request) {
						CrudService.arAllRequest.filterFunction = null;
						CrudService.arAllRequest.refresh();
						return true;
					}
				}					
			}
			
			function filterForReq(req:Object) : Boolean {
				return (req.name == man_name) ? true : false;
			}	
			
			CrudService.arAllRequest.filterFunction = null;
			CrudService.arAllRequest.refresh();
			
			return false;			
		}*/
		
	}
}